const http = require('http')
const qs=require('querystring')
const config = require('../config')
const setStorage=require('../Redis/setStorage')
const UserService=require('../service/UserService')
const uuidv1=require('uuid/v1')

const userSignin = async (ctx,next) => { //用户登录
    let postdata=qs.stringify(ctx.request.body)
    const result=new Promise((resolve,reject) => {
        let opt={
            hostname:config.hostname,
            port: config.port,
            path:'/user/signin',
            method: "POST",
            headers:{
                'Content-Type': 'application/x-www-form-urlencoded',
                'Content-Length': postdata.length
            }
        }
        let req=http.request(opt,(res) => {
            res.setEncoding('utf8')
            let resdata=''
            res.on('data',(chunk) => {
                resdata+=chunk
            })
            res.on('end',() => {
                let data=JSON.parse(resdata)
                if(data.code==200){
                    let userinfo=JSON.parse(data.data)
                    ctx.session.userId=userinfo.userId
                    ctx.session.email=userinfo.email
                }
                resolve(JSON.parse(resdata))
            })
        })
        req.on('error',(e) => {
            reject(e)
        })
        req.write(postdata)
        req.end()
    })
    let data=await result
    if(data.code){
        ctx.error(data)
    }else{
        ctx.success(data)
    }
}

const userBasicInfo = async (ctx) => { //请求用户信息
    const userid =  ctx.session.userId
    if(userid){
        const result = new Promise((resolve, reject) => {
            let opt={
                hostname:config.hostname,
                port:config.port,
                path:`/user/basic/${userid}`,
                method:'GET'
            }
            let req = http.request(opt,(res) => {
                res.setEncoding('utf8');
                let userdata = '';
                res.on('data', (data) => {
                    userdata += data
                });
                res.on('end', () =>{
                    let jsondata=JSON.parse(userdata)
                    let data=Object.assign(jsondata.data,jsondata.data2)
                    resolve(data)
                });
            })
            req.on('error', (e) => {
                reject(e)
            })
            req.end()
        })
        return result
    }else{
        return []
    }
}
const Basicemailinformation = async (ctx,next) => { //邮箱请求用户信息
    let {email}=ctx.request.body
    let params={email:email}
    let postdata=qs.stringify(params)
    const result = new Promise((resolve, reject) => {
        let opt={
            hostname:config.hostname,
            port:config.port,
            path:`/user/public`,
            // path:`/user/public${email}`,
            method:'POST',
            headers:{
                'Content-Type': 'application/x-www-form-urlencoded',
                'Content-Length': postdata.length
            }
        }
        let req=http.request(opt,(res) => {
            res.setEncoding('utf8')
            let resdata=''
            res.on('data',(chunk) => {
                resdata+=chunk
            })
            res.on('end',() => {
                resolve(JSON.parse(resdata))
            })
        })
        req.on('error',(e) => {
            reject(e)
        })
        req.write(postdata)
        req.end()
    })
    let data=await result
    if(data.code){
        ctx.error(data)
    }else{
        ctx.success(data)
    }
}
const profilePicture = async (ctx,next) => { //上传用户头像
    const userId = ctx.session.userId
    let {base64url} = ctx.request.body
    let params={userId:userId,avatar:base64url}
    let postdata=qs.stringify(params)
    const result = new Promise((resolve, reject) => {
        let opt={
            hostname:config.hostname,
            port:config.port,
            path:`/upload/uploadImage`,
            method:'POST',
            headers:{
                'Content-Type': 'application/x-www-form-urlencoded',
                'Content-Length': postdata.length
            }
        }
        let req=http.request(opt,(res) => {
            res.setEncoding('utf8')
            let resdata=''
            res.on('data',(chunk) => {
                resdata+=chunk
            })
            res.on('end',() => {
                resolve(JSON.parse(resdata))
            })
        })
        req.on('error',(e) => {
            reject(e)
        })
        req.write(postdata)
        req.end()
    })
    let data=await result
    if(data.code&&data.code!=200){
        ctx.error(data)
    }else{
        ctx.success(data)
    }
}
const userRegister = async (ctx,next) => { //用户注册
    let params=ctx.request.body
    params=Object.assign(params,{registerIp:String(ctx.ip)})
    let postdata=qs.stringify(params)
    const result=new Promise((resolve,reject) => {
        let opt={
            hostname:config.hostname,
            port: config.port,
            path:`/user/register?${postdata}`,
            method: "PUT",
        }
        let req=http.request(opt,(res) => {
            res.setEncoding('utf8')
            let resdata=''
            res.on('data',(chunk) => {
                resdata+=chunk
            })
            res.on('end',() => {
                resolve(JSON.parse(resdata))
            })
        })
        req.on('error',(e) => {
            reject(e)
        })
        req.end()
    })
    let data=await result
    if(data.code){
        ctx.error(data)
    }else{
        ctx.success(data)
    }
}

const changePassword = async (ctx,next) => { //修改密码
    let userId =  ctx.session.userId
    let params=Object.create(null)
    let {password,newPassword,checkCode}=ctx.request.body
    params={userId:userId,password:password,newPassword:newPassword,checkCode:checkCode}
    let postdata=qs.stringify(params)
    const result = new Promise((resolve, reject) => {
        let opt={
            hostname:config.hostname,
            port:config.port,
            path:`/user/updateUserPassword`,
            method:'POST',
            headers:{
            'Content-Type': 'application/x-www-form-urlencoded',
            'Content-Length': postdata.length
            }
        }
        let req=http.request(opt,(res) => {
            res.setEncoding('utf8')
            let resdata=''
            res.on('data',(chunk) => {
                resdata+=chunk
            })
            res.on('end',() => {
                resolve(JSON.parse(resdata))
            })
        })
        req.on('error',(e) => {
            reject(e)
        })
        req.write(postdata)
        req.end()
    })
    let data=await result
    if(data.code&&data.code!=200){
        ctx.error(data)
    }else{
        ctx.success(data)
    }
}
const chooseLanguage = async (ctx,next) => { //切换语言
    let {lang}=ctx.request.body
    ctx.cookies.set('lang',lang,{
        httpOnly: false,  // 是否只用于http请求中获取
        overwrite: false  // 是否允许重写
    })
    ctx.success(20011)
}

const usersignout = async (ctx,next) => { //退出登录
    ctx.session=null
    ctx.success(200)
}

const updateBasicInfo = async (ctx,next) => { //更改用户信息
    let {nickname}=ctx.request.body
    const userId =  ctx.session.userId
    let params={nickname:nickname,id:userId}
    let postdata=qs.stringify(params)
    if(userId){
        const result = new Promise((resolve,reject) => {
            let opt={
                hostname:config.hostname,
                port: config.port,
                path:`/user/updateBasic`,
                method: "POST",
                headers:{
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Content-Length': postdata.length
                }
            }
            let req=http.request(opt,(res) => {
                res.setEncoding('utf8')
                let resdata=''
                res.on('data',(chunk) => {
                    resdata+=chunk
                })
                res.on('end',() => {
                    resolve(JSON.parse(resdata))
                })
            })
            req.on('error',(e) => {
                reject(e)
            })
            req.write(postdata)
            req.end()
        })
        let data=await result
        if(data.code){
            ctx.error(data)
        }else{
            ctx.success(data)
        }
    }
}

const usersetredis = async (ctx,next) => { // 设置用户redis缓存数据
    const userid =ctx.session.userId
    let data=Object.create(null)
    if(userid){
        let email=ctx.session.email
        let uuid=uuidv1()
        setStorage.setredis(uuid,email)
        data.code=200
        data.data=uuid
        ctx.success(data)
    }else{
        data.code=200
        data.data='fail'
        ctx.error(data)
    }
}

const userinvitation = async (ctx,next) => { //获取推广用户列表
    const userid =ctx.session.userId
    let getdata=qs.stringify(ctx.request.body)
    if(userid){
        const result = new Promise((resolve, reject) => {
            let opt={
                hostname:config.hostname,
                port:config.port,
                path:`/user/invitation/${userid}?${getdata}`,
                method:'GET'
            }
            let req=http.request(opt,(res) => {
                res.setEncoding('utf8')
                let resdata=''
                res.on('data',(chunk) => {
                    resdata+=chunk
                })
                res.on('end',() => {
                    resolve(JSON.parse(resdata))
                })
            })
            req.on('error',(e) => {
                reject(e)
            })
            req.end()
        })
        let data=await result
        if(data.code&&data.code!=200){
            ctx.error(data)
        }else{
            ctx.success(data)
        }
    }else{
        let data=Object.create(null)
        data.code=200
        data.data={}
        ctx.success(data) 
    }
}

const usercommision = async (ctx,next) => {  //移动端推广详情
    const userid =ctx.session.userId
    let getdata=qs.stringify(ctx.request.body)
    if(userid){
        const result = new Promise((resolve, reject) => {
            let opt={
                hostname:config.hostname,
                port:config.port,
                path:`/user/commision/${userid}?${getdata}`,
                method:'GET'
            }
            let req=http.request(opt,(res) => {
                res.setEncoding('utf8')
                let resdata=''
                res.on('data',(chunk) => {
                    resdata+=chunk
                })
                res.on('end',() => {
                    let data=Object.create(null)
                    let data2=Object.create(null)
                    data2.data2=JSON.parse(resdata).data2
                    data.code=JSON.parse(resdata).code
                    data.data=Object.assign(JSON.parse(resdata).data1,data2)
                    resolve(data)
                })
            })
            req.on('error',(e) => {
                reject(e)
            })
            req.end()
        })
        let data=await result
        if(data.code&&data.code!=200){
            ctx.error(data)
        }else{
            ctx.success(data)
        }
    }else{
        let data=Object.create(null)
        data.code=200
        data.data={}
        ctx.success(data) 
    }
}

const userMobileCommision = async (ctx,next) => { //推广详情
    const userid =ctx.session.userId
    let getdata=qs.stringify(ctx.request.body)
    if(userid){
        const result = new Promise((resolve, reject) => {
            let opt={
                hostname:config.hostname,
                port:config.port,
                path:`/user/mobile/commision/${userid}?${getdata}`,
                method:'GET'
            }
            let req=http.request(opt,(res) => {
                res.setEncoding('utf8')
                let resdata=''
                res.on('data',(chunk) => {
                    resdata+=chunk
                })
                res.on('end',() => {
                    let data=Object.create(null)
                    let data2=Object.create(null)
                    data2.data2=JSON.parse(resdata).data2
                    data.code=JSON.parse(resdata).code
                    data.data=Object.assign(JSON.parse(resdata).data1,data2)
                    resolve(data)
                })
            })
            req.on('error',(e) => {
                reject(e)
            })
            req.end()
        })
        let data=await result
        if(data.code&&data.code!=200){
            ctx.error(data)
        }else{
            ctx.success(data)
        }
    }else{
        let data=Object.create(null)
        data.code=200
        data.data={}
        ctx.success(data) 
    }
}
const eamilcheck = async (ctx,next) => { //验证邮箱是否存在
    let getdata=qs.stringify(ctx.request.body)
    const result = new Promise((resolve, reject) => {
        let opt={
            hostname:config.hostname,
            port:config.port,
            path:`/user/check?${getdata}`,
            method:'GET'
        }
        let req=http.request(opt,(res) => {
            res.setEncoding('utf8')
            let resdata=''
            res.on('data',(chunk) => {
                resdata+=chunk
            })
            res.on('end',() => {
                resolve(JSON.parse(resdata))
            })
        })
        req.on('error',(e) => {
            reject(e)
        })
        req.end()
    })
    let data=await result
    if(data.code&&data.code!=200){
        ctx.error(data)
    }else{
        ctx.success(data)
    }
}

module.exports = {
    userBasicInfo,
    Basicemailinformation,
    userSignin,
    userRegister,
    chooseLanguage,
    usersignout,
    changePassword,
    updateBasicInfo,
    profilePicture,
    usersetredis,
    userinvitation,
    usercommision,
    userMobileCommision,
    eamilcheck
}